package com.zqwm.fly.utils;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by w-zhu on 2017/4/5.
 */
public class Util {
	
	private static Logger logger = LoggerFactory.getLogger(Util.class);
    static double DEF_PI = 3.14159265359; // PI
    static double DEF_2PI= 6.28318530712; // 2*PI
    static double DEF_PI180= 0.01745329252; // PI/180.0
    static double DEF_R =6370693.5; // radius of earth
    private static SimpleDateFormat sdfyMdHms=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static SimpleDateFormat sdfyMdHmsTradeNo=new SimpleDateFormat("yyyyMMddHHmmss");
    private static SimpleDateFormat sdfyMd=new SimpleDateFormat("yyyy-MM-dd");
    private static DecimalFormat gps6=new DecimalFormat("#0.000000");

    public static double GetShortDistance(double lon1, double lat1, double lon2, double lat2)
    {
        double ew1, ns1, ew2, ns2; 
        double dx, dy, dew;
        double distance;
        // 角度转换为弧度
        ew1 = lon1 * DEF_PI180;
        ns1 = lat1 * DEF_PI180;
        ew2 = lon2 * DEF_PI180;
        ns2 = lat2 * DEF_PI180;
        // 经度差
        dew = ew1 - ew2;
        // 若跨东经和西经180 度，进行调整
        if (dew > DEF_PI)
            dew = DEF_2PI - dew;
        else if (dew < -DEF_PI)
            dew = DEF_2PI + dew;
        dx = DEF_R * Math.cos(ns1) * dew; // 东西方向长度(在纬度圈上的投影长度)
        dy = DEF_R * (ns1 - ns2); // 南北方向长度(在经度圈上的投影长度)
        // 勾股定理求斜边长
        distance = Math.sqrt(dx * dx + dy * dy);
        return distance;
    }
    //适用于远距离
    public static double GetLongDistance(double lon1, double lat1, double lon2, double lat2)
    {
        double ew1, ns1, ew2, ns2;
        double distance;
        // 角度转换为弧度
        ew1 = lon1 * DEF_PI180;
        ns1 = lat1 * DEF_PI180;
        ew2 = lon2 * DEF_PI180;
        ns2 = lat2 * DEF_PI180;
        // 求大圆劣弧与球心所夹的角(弧度)
        distance = Math.sin(ns1) * Math.sin(ns2) + Math.cos(ns1) * Math.cos(ns2) * Math.cos(ew1 - ew2);
        // 调整到[-1..1]范围内，避免溢出
        if (distance > 1.0)
            distance = 1.0;
        else if (distance < -1.0)
            distance = -1.0;
        // 求大圆劣弧长度
        distance = DEF_R * Math.acos(distance);
        return distance;
    }

    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception
    {
        if (map == null) return null;

        Object obj = beanClass.newInstance();

        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors)
        {
            Method setter = property.getWriteMethod();
            if (setter != null){setter.invoke(obj, map.get(property.getName()));}
        }

        return obj;
    }

    public static Map<String, Object> sortMapByKey(Map<String, Object> oriMap)
    {
        if (oriMap == null || oriMap.isEmpty()){return null;}

        Map<String, Object> sortedMap = new TreeMap<String, Object>(new Comparator<String>() {
            public int compare(String key1, String key2) {
                int intKey1 = 0, intKey2 = 0;
                try {
                    intKey1 = getInt(key1);
                    intKey2 = getInt(key2);
                } catch (Exception e) {
                    intKey1 = 0;
                    intKey2 = 0;
                }
                return intKey1 - intKey2;
            }});
        sortedMap.putAll(oriMap);
        return sortedMap;
    }

    private static int getInt(String str)
    {
        int i = 0;
        try {
            Pattern p = Pattern.compile("^\\d+");
            Matcher m = p.matcher(str);
            if (m.find()){i = Integer.valueOf(m.group());}
        } catch (NumberFormatException e) {
        	logger.error("getInt", e);
        }

        return i;
    }
    
    public static long getYMdHmsTime(String dateYMdHms){
    	long planseconds=0;
    	try {
			planseconds=sdfyMdHms.parse(dateYMdHms).getTime();
		} catch (Exception e) {
			logger.error("getYMdHmsTime", e);
		}
    	return planseconds;
    }
    
    public static String getYMdHms(Date date){
    	return sdfyMdHms.format(date);
    }
    
    public static String getYMdHmsTradeNo(Date date){
    	return sdfyMdHmsTradeNo.format(date);
    }
    
    public static String getYMd(Date date){
    	return sdfyMd.format(date);
    }
    
    public static String getGPS6(Double str){
    	return gps6.format(str);
    }
    
    public static JSONObject doGetGaodeData(String origins,String destination,String key) {
    	InputStream in = null;
    	JSONObject resultJson = null;
        try {
			URL localURL = new URL("http://restapi.amap.com/v3/distance?type=1&origins="+origins+"&destination="+destination+"&key="+key);
			URLConnection connection = localURL.openConnection();
			
			HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
			httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
			httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			
			if (httpURLConnection.getResponseCode() <= 300) {
				in = httpURLConnection.getInputStream();
				JSONObject json=new JSONObject(StreamUtil.stream2String(in));
				if("1".equals(json.getString("status"))&&"OK".equals(json.getString("info"))){
					resultJson=json.getJSONArray("results").getJSONObject(0);
				}
			}
		} catch (Exception e) {
			logger.error("getInt", e);
		}finally {
            try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				logger.error("getInt", ex);
			}
        }
        return resultJson;
    }
    
    public static String doGetwwlt(String url) {
    	InputStream in = null;
    	String result = null;
    	try {
    		URL localURL = new URL(url);
    		URLConnection connection = localURL.openConnection();
    		
    		HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
    		httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
    		httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    		
    		if (httpURLConnection.getResponseCode() <= 300) {
    			in = httpURLConnection.getInputStream();
    			result=StreamUtil.stream2String(in);
    		}
    	} catch (Exception e) {
    		logger.error("getInt", e);
    	}finally {
    		try {
    			if (in != null) {
    				in.close();
    			}
    		} catch (IOException ex) {
    			logger.error("getInt", ex);
    		}
    	}
    	return result;
    }
    
}
